"""
国际化（i18n）管理器
支持多语言切换和动态文本翻译
"""

import json
import os
from typing import Dict, Any, Optional
from core.utils.logger import debug, info, error, warning
from core.services.data_manager import DataManager


class I18nManager:
    """国际化管理器 - 单例模式"""
    
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(I18nManager, cls).__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self.dm = DataManager()
            self.current_language = "en_US"  # 默认英文
            self.translations = {}
            self.locales_dir = os.path.join(self.dm.data_dir, "locales")
            self._ensure_locales_dir()
            self._load_language(self.current_language)
            I18nManager._initialized = True
            info(f"I18nManager initialized with language: {self.current_language}")
    
    def _ensure_locales_dir(self):
        """确保语言包目录存在"""
        try:
            os.makedirs(self.locales_dir, exist_ok=True)
            debug(f"📁 Locales directory ensured: {self.locales_dir}")
        except Exception as e:
            error(f"Failed to create locales directory: {e}")
    
    def _load_language(self, lang_code: str) -> bool:
        """加载指定语言的语言包"""
        try:
            lang_file = os.path.join(self.locales_dir, f"{lang_code}.json")
            if not os.path.exists(lang_file):
                warning(f"Language file not found: {lang_file}")
                return False
            
            with open(lang_file, 'r', encoding='utf-8') as f:
                self.translations = json.load(f)
            
            self.current_language = lang_code
            info(f"Loaded language: {lang_code}")
            return True
            
        except Exception as e:
            error(f"Failed to load language {lang_code}: {e}")
            return False
    
    def set_language(self, lang_code: str) -> bool:
        """切换语言"""
        if lang_code == self.current_language:
            return True
        
        success = self._load_language(lang_code)
        if success:
            # 保存语言设置到配置文件
            self._save_language_setting(lang_code)
        return success
    
    def _save_language_setting(self, lang_code: str):
        """保存语言设置到配置文件"""
        try:
            settings = self.dm.load_data('settings.json') or {}
            settings['language'] = lang_code
            self.dm.save_data('settings.json', settings)
            debug(f"💾 Saved language setting: {lang_code}")
        except Exception as e:
            error(f"Failed to save language setting: {e}")
    
    def get_current_language(self) -> str:
        """获取当前语言代码"""
        return self.current_language
    
    def t(self, key: str, **kwargs) -> str:
        """
        翻译函数
        Args:
            key: 翻译键，支持点号分隔的嵌套键，如 "welcome.title"
            **kwargs: 用于字符串格式化的参数
        Returns:
            翻译后的文本，如果找不到则返回原键
        """
        try:
            # 支持嵌套键，如 "welcome.title"
            keys = key.split('.')
            value = self.translations
            
            for k in keys:
                if isinstance(value, dict) and k in value:
                    value = value[k]
                else:
                    # 找不到键，返回原键
                    warning(f"Translation key not found: {key}")
                    return key
            
            # 如果找到的值是字符串，进行格式化
            if isinstance(value, str):
                if kwargs:
                    try:
                        return value.format(**kwargs)
                    except (KeyError, ValueError) as e:
                        warning(f"String formatting failed for key '{key}': {e}")
                        return value
                return value
            else:
                warning(f"Translation value is not a string for key '{key}': {type(value)}")
                return key
                
        except Exception as e:
            error(f"Translation error for key '{key}': {e}")
            return key
    
    def get_available_languages(self) -> list:
        """获取可用的语言列表"""
        try:
            languages = []
            for file in os.listdir(self.locales_dir):
                if file.endswith('.json'):
                    lang_code = file[:-5]  # 去掉 .json 后缀
                    languages.append(lang_code)
            return languages
        except Exception as e:
            error(f"Failed to get available languages: {e}")
            return ["zh_CN", "en_US"]  # 默认返回
    
    def reload_current_language(self) -> bool:
        """重新加载当前语言"""
        return self._load_language(self.current_language)
    
    def get_language_display_name(self, lang_code: str) -> str:
        """获取语言的显示名称"""
        display_names = {
            "zh_CN": "中文",
            "en_US": "English"
        }
        return display_names.get(lang_code, lang_code)


# 全局单例实例
i18n = I18nManager()


def t(key: str, **kwargs) -> str:
    """
    全局翻译函数，方便使用
    Args:
        key: 翻译键
        **kwargs: 格式化参数
    Returns:
        翻译后的文本
    """
    return i18n.t(key, **kwargs)


def set_language(lang_code: str) -> bool:
    """
    全局语言切换函数
    Args:
        lang_code: 语言代码
    Returns:
        是否切换成功
    """
    return i18n.set_language(lang_code)


def get_current_language() -> str:
    """获取当前语言"""
    return i18n.get_current_language()
